

'use strict';

const express = require('express');
const path = require('path');
const xtpl = require('xtpl');

// 引入数据库文件

const db = require(path.join(__dirname,"../configs/database.js"));

const base = require(path.join(__dirname,"./baseController.js"));



module.exports.teachList=function(req,res){

  const page=parseInt(req.query.page||'1');
  const limit=parseInt(req.query.limit||'12');
  const start=(page-1)*limit;

  // 查询总数


  db.table('teach').count("*").then(function(count){
       
       const totalPage=count%limit==0?count/limit:parseInt(count/limit)+1;

       const totalPageArray=[];

       for(var i=1;i<=totalPage;i++){
             totalPageArray.push(i);
       }


 // 查询教师表里面的所有数据

  db.table('teach').order('teach_id DESC').limit(start,limit).select().then(function(data){


   xtpl.renderFile(

    path.join(__dirname,"../views/admin/teach/teach_list.html"),
    {

                   array:data,
                    totalPageArray:totalPageArray,
                    page:page,
                    totalPage:totalPage
    },

    function(err,content){
        
        if(err){

         return console.log(err);

        }

      res.setHeader('Content-Type','text/html;charset=utf-8');
      res.end(content);
    }

    );

  });

  })

};


// 教师添加界面


module.exports.teachAdd = function(req,res){

    xtpl.renderFile(
        path.join(__dirname,"../views/admin/teach/teach_add.html"),
        {},
        function(err,content)
        {
            res.setHeader("Content-Type","text/html;charset=utf-8");
            res.end(content);
        }
    );
};

// 就收post提交的数据  req 请求的数据  res响应的数据

module.exports.teachAddData=function(req,res){

 const where = `teach_name = '${req.body.teach_name}'`;

 db.table("teach").where(where).find().then(function(data){
   
     if(JSON.stringify(data)!="{}"){

          res.setHeader("Content-Type","text/html;charset=utf-8");  
          // 跳转回路由
           res.end("<script>alert('该教师已经存在，请重新添加');location.href='/teach/teach_add';</script>"); 
          return false;
     }else{
       
       // 封装数据部分
        
        const data={
        	 "teach_name":req.body.teach_name,
        	 "teach_sex":req.body.teach_sex,
        	 "teach_tel":req.body.teach_tel,
        	 "teach_qq":req.body.teach_qq
        };

        // 把就收的数据入库
      db.table('teach').add(data).then(function(insertId){

           res.redirect('/teach/teach_add');

           return false;

      }).catch(function(err){

          if(err){
              return console.log(err);
          }
      });
     }
 });

};


// 来到教师编辑界面

module.exports.teachEdit=function(req,res){


  var teach_id=req.params.teach_id||0;
  var where = `teach_id=${teach_id}`;
  
  // 返回就数据
  db.table('teach').where(where).find().then(function(data){
     if(JSON.stringify(data)=="{}"){
          base.showMsg(res,'教师不存在','/teach/teach_list');
          return false;
     }else{
       xtpl.renderFile(
       path.join(__dirname,'../views/admin/teach/teach_edit.html'),
       {
         
         teachInfo:data

       },
       function(err,content){
         res.setHeader('Content-Type','text/html;charset=utf-8');
         res.end(content);
       }

        );
     }
  });
};

// 数据修改界面

module.exports.teachEditAdd=function(req,res){

  
  var teach_id=req.params.teach_id || 0;

  var where=`teach_id=${teach_id}`;

  db.table('teach').where(where).find().then(function(data){

     if(JSON.stringify(data)=="{}"){
         
          base.showMsg(res,'教师不存在','/teach/teach_edit');
          return false;

     }else{

        var check= `teach_name='${req.body.teach_name}' AND teach_id !=${teach_id} `;
        
        db.table('teach').where(check).find().then(function(data){
          
          if(JSON.stringify(data)!="{}"){
             
             base.showMsg(res,'教师已经存在');
             return false;
          }else{

        const data={
           "teach_name":req.body.teach_name,
           "teach_sex":req.body.teach_sex,
           "teach_tel":req.body.teach_tel,
           "teach_qq":req.body.teach_qq
        };

     db.table('teach').where(`teach_id=${teach_id}`).update(data).then(function(affectRows){
                   res.redirect('/teach/teach_list');
                   return false;

              }).catch(function(err){

              if(err){
                    base.showMsg(res,"更新失败");
                    console.log(err);
                    return false;
                };
              });
          }

        });

     }

  });

}


//删除老师 要删除班级 删除班级 就要删除班级里面的学生
module.exports.teachDelte=function(req,res){

  const teach_id=req.params.teach_id||0;
 

 console.log(teach_id);

  const where=`teach_id='${teach_id}'`;

  // 删除学生
  
  db.table('student').where(where).delete().then(function(studentRows){
   
    //删除班级
    
    db.table('class').where(where).delete().then(function(classRows){

        // 删除老师
        db.table('teach').where(where).delete().then(function(teachRows){
            base.showMsg(res,'教师删除成功','/teach/teach_list');
            return false;

        }).catch(function(err){
            base.showMsg(res,'删除失败','/teach/teach_list');
            return false;

        });

    }).catch(function(err){

       base.showMsg(res,'删除失败','/teach/teach_list');
       return false;

    });

  }).catch(function(err){

       base.showMsg(res,'删除失败','/teach/teach_lsit');
       console.log(err);
       return false;


  });
}


